import requests
from .pubmed_tool import search_europepmc


headers = {
    "User-Agent": "PostmanRuntime-ApipostRuntime/1.1.0",
    "Accept": "*/*",
    "Accept-Encoding":"gzip, deflate, br",
    "Cache-Control":"no-cache",
    "Host":"api.crossref.org",
    "Connection":"keep-alive"
}

def build_query(
        title = None,
        author = None,
        container_title = None,
        rows=3,
):

    params = {}
    if title:
        params["query.title"] = title
    if author:
        params["query.author"] = author
    if container_title:
        params["query.container-title"] = container_title


    if rows:
        params["rows"]  =rows


    return params


def search(
        title = None,
        author = None,
        container_title = None,
        rows = 3,
        download_pdf=False,
        save_dir="./papers"
):
    """

    :param title: 论文标题
    :param author: 作者
    :param container_title: 期刊名称
    :param rows: 展示条目数量
    :return:
    """
    url = "https://api.crossref.org/works"
    params= build_query(title,author,container_title,rows)

    for i in range(10):
        r = requests.get(url,params, headers=headers)

        status_code = r.status_code
        if status_code==200:
            break

    data = r.json()

    results = []
    for item in data["message"]["items"]:
        doi = item["DOI"] # DOI
        result = search_europepmc(doi,download_pdf,save_dir)[0]
        result["authors"] = result.get("authors") if result.get("authors") is not None else [
            author.get("family", "") + " " + author.get("given", "") for author in item.get("author", [])
        ]

        result["title"] = result.get("title") if result.get("title") is not None else (
            item.get("title", [""])[0]
        )
        # journalTitle（取 container-title 中的第一个期刊名）
        result["journalTitle"] = result.get("journalTitle") if result.get("journalTitle") is not None else (
            item.get("container-title", [""])[0]
        )
        result["resource_url"] = item["resource"]["primary"]["URL"]

        results.append(result)

    return results


if __name__ == '__main__':
    search("唾液皮质醇和睾酮水平与军事应激的相关性")

